package com.zhx.bussiness.service.impl;

import com.zhx.business.api.ProductRpc;
import com.zhx.business.entity.Order;
import com.zhx.business.entity.Product;
import com.zhx.business.enums.OrderStatus;
import com.zhx.business.enums.OrderType;
import com.zhx.business.repository.OrderRepository;
import com.zhx.bussiness.service.OrderServiceInf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.UUID;

/**
 * describe:
 *
 * @author zhanghaixuan
 * @date 2018/06/14
 **/
@Service
public class OrderServiceImpl implements OrderServiceInf {

    @Autowired
    private ProductRpc productRpc;

    @Autowired
    private OrderRepository orderRepository;

    /**
     * 申购订单
     *
     * @param order
     * @return
     */
    @Override
    public Order apply(Order order) {
        //数据校验
        checkOrder(order);
        //完善订单数据
        completeOrder(order);
        order = orderRepository.saveAndFlush(order);
        return order;
    }

    /**
     * 完善订单数据
     *
     * @param order
     */
    private void completeOrder(Order order) {
        order.setUid(UUID.randomUUID().toString().replaceAll("-", ""));
        order.setOrderType(OrderType.APPLY.name());
        order.setOrderStatus(OrderStatus.SUCCESS.name());
    }

    /**
     * 校验数据
     *
     * @param order
     */
    private void checkOrder(Order order) {
        //必填字段
        Assert.notNull(order.getOutOrderId(), "需要外部订单编号");
        Assert.notNull(order.getChanId(), "需要渠道编号");
        Assert.notNull(order.getChanUserId(), "需要用户编号");
        Assert.notNull(order.getProductId(), "需要产品编号");
        Assert.notNull(order.getAmount(), "需要购买金额");

        //产品是否存在及金额是否符合要求
        Product one = productRpc.findOne(order.getProductId());
        Assert.notNull(one, "产品不存在");
        //金额要满足如果有起投金额时，要大于等于起投金额，如果有投资步长时，超过起投金额的部分要是投资步长的整数倍
    }

}
